﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App_Code;
using System.Configuration;
using System.Collections.Specialized;
using DM4;


namespace Pages.Account
{
    public partial class LoginPage : Page
    {
        // ReSharper disable InconsistentNaming
        protected void Page_Load(object sender, EventArgs e)
        // ReSharper restore InconsistentNaming
        {
            CommonVars.SelectedUid = -1;
            if (IsPostBack) return;

            if (IsCookieDisabled())
                FailureText.Text = "Cookies are disabled. Enable cookies, please";

            InitPage();
        }

        /// <summary>
        /// Init page controls.
        /// </summary>
        private void InitPage()
        {
            try
            {
                Page.Title = CommonVars.LoginPageTitle;
                ServerNameRequired.ToolTip = StringMessages.ServerNameRequirement;
                ServerNameRequired.ErrorMessage = StringMessages.ServerNameRequirement;

                UserNameRequired.ToolTip = StringMessages.UserNameRequirement;
                UserNameRequired.ErrorMessage = StringMessages.UserNameRequirement;

                PasswordRequired.ToolTip = StringMessages.PasswordRequirement;
                PasswordRequired.ErrorMessage = StringMessages.PasswordRequirement;

                FillServerNameDdl();//fill select list with server names, try to set previous server

                //set user login
                HttpCookie cLogin = Request.Cookies[CommonVars.Login];
                if (cLogin != null && !string.IsNullOrEmpty(cLogin.Value) && cLogin.Value != DM4Consts.ErrorUnknown.ToString())
                    UserName.Text = cLogin.Value;

            }
            catch (Exception ex)
            {
                CommonProc.SetLastError(ex.Message);
                FailureText.Text = CommonVars.LastError;
            }
        }

        /// <summary>
        /// Try to login, set cookies, if success
        /// </summary>
        protected void LoginButtonClick(object sender, EventArgs e)
        {
            CommonVars.LastError = "";
            if (CommonProc.CreateServerChannel(ddlServerName.SelectedValue))
            {
                if (CommonProc.ServerLogin(UserName.Text, Password.Text)
                    //&& CommonVars.Ui.Id != DM4Consts.ErrorUnknown
                    )
                {
                    Response.Cookies.Clear();
                   // Response.Cookies.Add(new HttpCookie(CommonVars.UserId, CommonVars.Ui.Id.ToString()));
                    Response.Cookies.Add(new HttpCookie(CommonVars.Login, UserName.Text));
                    Response.Cookies.Add(new HttpCookie(CommonVars.Password, Password.Text));
                    Response.Cookies.Add(new HttpCookie(CommonVars.EndpointAddress, ddlServerName.SelectedValue));
                    Response.Cookies.Add(new HttpCookie(CommonVars.EndpointServerName, ddlServerName.SelectedItem.Text));

                    Response.Redirect(CommonVars.DefaultPageRelUrl + "?LoginSuccess=true", true);
                }
                else
                    FailureText.Text = CommonVars.LastError;
            }
            else FailureText.Text = CommonVars.LastError;
        }

        /// <summary>
        /// <para>Fill select dropdown list with server names.</para> 
        /// <para>Try to set previous server from cookies.</para>
        /// </summary>
        private void FillServerNameDdl()
        {

            NameValueCollection nvcDbKeys = (NameValueCollection)ConfigurationManager.GetSection(CommonVars.WebConfigServerNamesSection);
            ddlServerName.Enabled = false;
            ddlServerName.Items.Clear();
            for (int i = 0; i < nvcDbKeys.Count; i++)
                ddlServerName.Items.Add(new ListItem(nvcDbKeys.Keys[i], nvcDbKeys.Get(i)));

            HttpCookie c = Request.Cookies[CommonVars.EndpointAddress];
            if (c != null)
            {
                string curval = c.Value;
                if (!string.IsNullOrEmpty(curval))
                    foreach (ListItem li in ddlServerName.Items)
                        if (li.Value == curval)
                            li.Selected = true;
            }
            ddlServerName.Enabled = true;
        }

        /// <summary>
        /// Check cookies support
        /// </summary>
        public bool IsCookieDisabled()
        {
            string currentUrl = Request.RawUrl;

            if (Request.QueryString["cookieCheck"] == null)
            {
                HttpCookie c = new HttpCookie("SupportCookies", "true");
                try
                {
                    Response.Cookies.Add(c);
                    if (currentUrl.IndexOf("?") > 0)
                        currentUrl = currentUrl + "&cookieCheck=true";
                    else
                        currentUrl = currentUrl + "?cookieCheck=true";

                    Response.Redirect(currentUrl, true);

                }
                // ReSharper disable EmptyGeneralCatchClause
                catch (Exception)
                // ReSharper restore EmptyGeneralCatchClause
                {
                }

            }

            if (!Request.Browser.Cookies || Request.Cookies["SupportCookies"] == null)
                return true;

            return false;
        }


    }
}